package com.hybrid.webview;

import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.hybrid.config.GlobalConfig;
import com.hybrid.jsbridge.WVPageFinishJSRender;
import com.hybrid.urlintercept.WVURLInterceptService;
import com.hybrid.utils.TaoLog;
import com.hybrid.utils.WVConstants;

public class WVWebViewClient extends WebViewClient {
    private static final String TAG = "WVWebViewClient";
    protected Context mContext;

    private boolean isAppcacheEnabled = false;

    protected  boolean openAllspdytake = false;

    private String currentUrl = null;

    public WVWebViewClient(Context context) {
        this.mContext = context;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        //发送生命周期通知
        //WVEventService.getInstance().onEvent(WVEventId.PAGE_Started, view, url);
        if (TaoLog.getLogStatus()) {
            TaoLog.v(TAG, "Page start: " + url);
        }
        isAppcacheEnabled = false;
        currentUrl = url;
        //发送消息
        ((WVWebView) view).onMessage(WVConstants.NOTIFY_PAGE_START, url);
        //埋点
        //if (WVMonitorService.getPerformanceMonitor() != null) {
        //    WVMonitorService.getPerformanceMonitor().didPageStartLoadAtTime(url, System.currentTimeMillis());
        //}
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        //WVEventService.getInstance().onEvent(WVEventId.PAGE_Finished, view, url);
        WVWebView webview = (WVWebView) view;
        if (TaoLog.getLogStatus()) {
            TaoLog.v(TAG, "Page finish: " + url);
        }

        //if (WVMonitorService.getPerformanceMonitor() != null) {
        //    WVMonitorService.getPerformanceMonitor().didPageFinishLoadAtTime(url, System.currentTimeMillis());
        //}
        webview.onMessage(WVConstants.NOTIFY_PAGE_FINISH, url);
        // WVJsPatch.getInstance().execute(view, url);
        //发送onPageFinished通知 给js
        webview.fireEvent("WindVaneReady", String.format("{'version':'%s'}", GlobalConfig.VERSION));

        //if (isAppcacheEnabled) {
        //    WVCacheManager.getInstance().removeCache(currentUrl);
        //}
        WVPageFinishJSRender.renderJSContent(webview);
    }

    /**
     * 页面加载失败
     * @param view
     * @param errorCode
     * @param description
     * @param failingUrl
     */
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        if (TaoLog.getLogStatus()) {
            TaoLog.v(TAG, "Receive error, code: " + errorCode + "; desc: " + description + "; url: " + failingUrl);
        }

        //if (WVEventService.getInstance().onEvent(WVEventId.PAGE_ReceivedError, view, failingUrl, errorCode, description, failingUrl).isSuccess) {
        //    return;
        //}

        String curl = view.getUrl();
        if (curl == null || curl.equals(failingUrl)) {
            ((WVWebView) view).onMessage(WVConstants.NOTIFY_PAGE_ERROR, failingUrl);
        }

        //if (WVMonitorService.getErrorMonitor() != null) {
        //    WVMonitorService.getErrorMonitor().didOccurNativeError(curl == null ? failingUrl : curl, errorCode, description);
        //}
        // DebugToolsHelper.sendStatusMsg(mContext, failingUrl,
        // DebugConstants.PageStatusEnum.ERROE.getValue(), errorCode + "|" +
        // description, 0);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        if (TaoLog.getLogStatus()) {
            TaoLog.v(TAG, "shouldOverrideUrlLoading: " + url);
        }

        //if (WVEventService.getInstance().onEvent(WVEventId.PAGE_OverrideUrlLoading, view, url).isSuccess) {
        //    return true;
        //}
        if (url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith(WebView.SCHEME_TEL)) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                TaoLog.e(TAG, "shouldOverrideUrlLoading: ActivityNotFoundException, url=" + url);
            }
            return true;
        }

        // url拦截
        try {
            if (WVURLInterceptService.getWVURLIntercepter() != null && WVURLInterceptService.getWVURLIntercepter().isOpenURLIntercept()) {

                if (WVURLInterceptService.getWVURLIntercepter().isNeedupdateURLRule(false)) {
                    WVURLInterceptService.getWVURLIntercepter().updateURLRule();
                }
                if (WVURLInterceptService.getWVURLIntercepter().shouldOverrideUrlLoading(url)) {
                    return true;

                }

            }
        } catch (Exception e) {
            TaoLog.e(TAG, "shouldOverrideUrlLoading: doFilter error, " + e.getMessage());
        }

        return false;
    }

    @TargetApi(11)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

        if (TaoLog.getLogStatus()) {
            TaoLog.v(TAG, "Intercept Request start, " + url);
        }
        //WVEventResult eventResult = WVEventService.getInstance().onEvent(WVEventId.PAGE_InterceptRequest, view, url);
        //if (eventResult.isSuccess && eventResult.resulteObj != null && eventResult.resulteObj instanceof WebResourceResponse) {
        //    return (WebResourceResponse) eventResult.resulteObj;
        //}

        /**
         * 带menifest的资源不缓存，走系统原生
         */
        if (!isAppcacheEnabled && url.endsWith(".manifest")) {
            isAppcacheEnabled = true;
        }

        //if (WVURLCacheService.getURLCacheSecurityHandler() != null
        //    && !WVURLCacheService.getURLCacheSecurityHandler().isSecurityRequest(url)) {
        //    WVURLCacheService.getURLCacheSecurityHandler().afterSecurityCheckerFailed();
        //}

        /**
         * 缓存开始的时候通知事件出去
         */
        //if (WVURLCacheService.getEventCallbacks() != null && !WVURLCacheService.getEventCallbacks().isEmpty()) {
        //    for (WVURLCacheProcessEventHandler handle : WVURLCacheService.getEventCallbacks()) {
        //        handle.cacheProcessStartEvent(url);
        //    }
        //
        //}
        /**
         * 缓存前置判断条件：
         * 1、scheme 为 data,https,带有_wvcrc=0或为空的时候，强制不缓存。
         * 2、是否符合缓存规则
         * 3、openAllspdytake=true的时候，用本地网络库接管webkit下载，不建议使用
         */

        //if (WVCacheManager.getInstance().canCached(url)
        //    &&(WVCacheManager.getInstance().isCacheEnabled(url)
        //    ||(openAllspdytake&&WVCacheManager.getInstance().canResTakedown(url)))) {
        //    WebResourceResponse Response = WVURLCacheService.getWVURLCache().getCache(view, url, currentUrl);
        //    if (Response != null) {
        //        /**
        //         * 缓存结束的时候通知事件出去
        //         */
        //        if (WVURLCacheService.getEventCallbacks() != null && !WVURLCacheService.getEventCallbacks().isEmpty()) {
        //            for (WVURLCacheProcessEventHandler handle : WVURLCacheService.getEventCallbacks()) {
        //                handle.cacheProcessEndEvent(url, Response);
        //            }
        //        }
        //        return Response;
        //
        //    }
        //}

        return super.shouldInterceptRequest(view, url);
    }

    //    @Override
    //    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, SslError error) {
    //        if (OpenLog.getLogStatus() && error != null) {
    //            OpenLog.w(TAG, "Receive ssl error: " + error.getPrimaryError());
    //        }
    //        if (mContext instanceof Activity) {
    //            AlertDialog.Builder dlg = new AlertDialog.Builder(mContext);
    //            dlg.setTitle("警告");
    //            dlg.setMessage("您访问的网址安全证书不受信任，是否继续?");
    //            dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
    //                public void onClick(DialogInterface dialog, int which) {
    //                    if (handler != null)
    //                        handler.proceed();
    //                    dialog.dismiss();
    //                }
    //            });
    //            dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
    //                public void onClick(DialogInterface dialog, int which) {
    //                    if (handler != null)
    //                        handler.cancel();
    //                    dialog.dismiss();
    //                    ((WVWebView) view).onMessage(WVConstants.NOTIFY_PAGE_ERROR, null);
    //                }
    //            });
    //            dlg.setOnCancelListener(new DialogInterface.OnCancelListener() {
    //                public void onCancel(DialogInterface dialog) {
    //                    if (handler != null)
    //                        handler.cancel();
    //                    dialog.dismiss();
    //                    ((WVWebView) view).onMessage(WVConstants.NOTIFY_PAGE_ERROR, null);
    //                }
    //            });
    //            dlg.create();
    //            dlg.show();
    //        } else {
    //            super.onReceivedSslError(view, handler, error);
    //        }
    //    }

}
